package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	_ "goravel/app/http/controllers/common"
	"goravel/app/http/requests"
	"goravel/app/models"
	"goravel/app/services/upload"
)

type UserController struct {
	//Dependent services
	UploadService upload.UploadService
}

func NewUserController() *UserController {
	return &UserController{
		//Inject services
	}
}

// Index 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         UserController
// @Accept       json
// @Produce      json
// @Id UserIndex
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/user [get]
func (r *UserController) Index(ctx http.Context) http.Response {
	users := []models.User{}
	queries := ctx.Request().Queries()
	res, err := httpfacade.NewResult(ctx).SearchByParams(queries, nil).ResultPagination(&users, "Roles")
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "", err.Error())
	}
	return res
}

// List 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         UserController
// @Accept       json
// @Produce      json
// @Id UserList
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  mobile  query  string  false  "mobile"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json {}
// @Router       /api/admin/user/list [get]
func (r *UserController) List(ctx http.Context) http.Response {
	users := []models.User{}
	queries := ctx.Request().Queries()
	return httpfacade.NewResult(ctx).SearchByParams(queries, nil).Success("", users)
}

func (r *UserController) Show(ctx http.Context) http.Response {
	return nil
}

// Store 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         UserController
// @Accept       json
// @Produce      json
// @Id UserStore
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param userData body requests.UserRequest true "用户数据"
// @Success 200 {string} json {}
// @Router       /api/admin/user [post]
func (r *UserController) Store(ctx http.Context) http.Response {
	var userRequest requests.UserRequest
	errors, err := ctx.Request().ValidateRequest(&userRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	user := models.User{}
	user.Name = userRequest.Name
	password, _ := facades.Hash().Make(userRequest.Password)
	user.Password = password
	facades.Orm().Query().Model(&models.User{}).Create(&user)
	return httpfacade.NewResult(ctx).Success("创建成功", nil)
}

// Destroy 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         UserController
// @Accept       json
// @Produce      json
// @Id UserDestroy
// @Security ApiKeyAuth
// @Param userData body requests.UserRequest true "用户数据"
// @Param Authorization header string false "Bearer 用户令牌"
// @Success 200 {string} json {}
// @Router       /api/admin/user/{id} [delete]
func (r *UserController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	user := models.User{}
	facades.Orm().Query().Model(&models.User{}).Where("id=?", id).Delete(&user, id)
	return httpfacade.NewResult(ctx).Success("删除成功", nil)
}

// Update 用户分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      用户分页查询
// @Description  用户分页查询
// @Tags         UserController
// @Accept       json
// @Produce      json
// @Id UserUpdate
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param userData body requests.UserRequest true "用户数据"
// @Success 200 {string} json {}
// @Router       /api/admin/user/{id} [put]
func (r *UserController) Update(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	user := models.User{}
	facades.Orm().Query().Model(&models.User{}).Where("id=?", id).Find(&user)
	var userRequest requests.UserRequest
	errors, err := ctx.Request().ValidateRequest(&userRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	password, _ := facades.Hash().Make(userRequest.Password)
	user.Password = password
	facades.Orm().Query().Model(&models.User{}).Where("id=?", id).Save(&user)
	return httpfacade.NewResult(ctx).Success("修改成功", nil)
}

// Profile returns the user profile.
// @Summary Get user profile
// @Description Get the current user's profile information.
// @Tags UserController
// @Accept json
// @Security BearerAuth
// @Produce json
// @Id UserProfile
// @Param Authorization header string true "Bearer token"
// @Success 200 {object} common.SuccessResponse "Successfully retrieved user profile."
// @Failure 400 {object} common.ErrorResponse "Bad request, invalid parameters."
// @Failure 401 {object} common.ErrorResponse "Unauthorized access."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID Profile
// @Router /api/admin/account/profile [get]
func (r *UserController) Profile(ctx http.Context) http.Response {
	var user models.User
	facades.Auth(ctx).User(&user)
	return httpfacade.NewResult(ctx).Success("", user)
}

// SetRole returns the user profile.
// @Summary Get user profile
// @Description Get the current user's profile information.
// @Tags UserController
// @Accept json
// @Security BearerAuth
// @Produce json
// @Id UserSetRole
// @Param roleData body interface{} true "部门数据"
// @Param Authorization header string true "Bearer token"
// @Failure 401 {object} common.ErrorResponse "Unauthorized access."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID SetRole
// @Router /api/admin/user/setrole [post]
func (r *UserController) SetRole(ctx http.Context) http.Response {
	role_ids := ctx.Request().InputArray("role_ids")
	user_id := ctx.Request().Input("user_id")
	user := models.User{}
	query := facades.Orm().Query()
	query.Where("id", user_id).First(&user)
	roles := []models.Role{}
	query.Where("id in (?)", role_ids).Find(&roles)
	facades.Orm().Query().Model(&user).Association("Roles").Clear()
	facades.Orm().Query().Model(&user).Association("Roles").Append(&roles)
	return httpfacade.NewResult(ctx).Success("设置成功", user)
}

// HasRole returns the user profile.
// @Summary Get user profile
// @Description Get the current user's profile information.
// @Tags UserController
// @Accept json
// @Security BearerAuth
// @Produce json
// @Id UserHasRole
// @Param Authorization header string true "Bearer token"
// @Param roleData body interface{} true "部门数据"
// @Failure 401 {object} common.ErrorResponse "Unauthorized access."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID UserHasRole
// @Router /api/admin/user/hasrole [post]
func (r *UserController) HasRole(ctx http.Context) http.Response {
	user_id := ctx.Request().Input("user_id")
	user := models.User{}
	query := facades.Orm().Query()
	query.Where("id", user_id).First(&user)
	roles := []models.Role{}
	facades.Orm().Query().Model(&user).Association("Roles").Find(&roles)
	return httpfacade.NewResult(ctx).Success("", roles)
}

// EmployeeList returns 维修工角色【employee_role】.
// @Summary Get user profile
// @Description Get the current user's profile information.
// @Tags UserController
// @Accept json
// @Security BearerAuth
// @Produce json
// @Id UserEmployeeList
// @Param Authorization header string true "Bearer token"
// @Failure 401 {object} common.ErrorResponse "Unauthorized access."
// @Failure 500 {object} common.ErrorResponse "Internal server error."
// @OperationID UserEmployeeRole
// @Router /api/admin/user/employee [get]
func (r *UserController) EmployeeList(ctx http.Context) http.Response {
	users := []models.User{}
	query := facades.Orm().Query()
	sql := `
SELECT u.*
FROM users u
JOIN role_user ur ON u.id = ur.user_id
JOIN roles r ON ur.role_id = r.id
WHERE r.value = 'employee_role';`
	query.Raw(sql).Scan(&users)
	return httpfacade.NewResult(ctx).Success("", users)
}
